package com.ckerchina.admin.ckadmin.utils.excel;

import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/***
 */
public abstract class ExportExcel<T> {
	
	public void exportExcel(HttpServletResponse response, String filename, List<T> list) throws Exception {
		OutputStream os = response.getOutputStream();
		response.reset();
		response.setHeader("Content-disposition", "attachment; filename=" + filename);
		response.setContentType("application/msexcel");// 定义输出类型
		
		WritableWorkbook workbook = Workbook.createWorkbook(os);
		WritableSheet sheet = workbook.createSheet("Sheet1", 0);
		jxl.SheetSettings sheetset = sheet.getSettings();
		sheetset.setProtected(false);

		// 用于标题居中
		WritableCellFormat wcf_center = new WritableCellFormat(new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD));//置单元格字体
		wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
		wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
		wcf_center.setAlignment(Alignment.CENTRE); // 文字水平对齐
		wcf_center.setWrap(false); // 文字是否换行
		
		// 用于正文居左
		WritableCellFormat wcf_left = new WritableCellFormat(new WritableFont(WritableFont.ARIAL, 10));
		wcf_left.setBorder(Border.NONE, BorderLineStyle.THIN); // 线条
		wcf_left.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
		wcf_left.setAlignment(Alignment.LEFT); // 文字水平对齐
		wcf_left.setWrap(false); // 文字是否换行
		
		doExport(sheet, wcf_center, wcf_left, list);
		workbook.write();
		workbook.close();
	}
	
	protected abstract void doExport(WritableSheet sheet, WritableCellFormat wcf_center, WritableCellFormat wcf_left, List<T> list) throws Exception;
}